const dns = require('dns');
const os = require('os');
const fs = require('fs');
const path = require('path');
const Koa = require('koa');
const app = new Koa();
const koaStatic = require('koa-static');
const Router = require('koa-router');
const router = new Router();
const { koaBody } = require('koa-body');
const sslify = require('koa-sslify').default;
const https = require('https');
const { createWorker } = require('tesseract.js');

const hostName = os.hostname();

app.use(koaStatic(path.join(__dirname, 'public')));
app.use(sslify());
app.use(koaBody({
  multipart: true,
  formidable: {
    // 上传目录
    uploadDir: path.join(__dirname, 'public/uploads'),
    // 保留文件扩展名
    keepExtensions: true,
  }
}))
app.use(router.routes())
app.use(router.allowedMethods())

router.post('/upload', async (ctx, next) => {
  if (ctx.request.files && ctx.request.files.file) {
    const file = ctx.request.files.file;
    if (file) {
      const basename = path.basename(file.filepath);
      const image = path.resolve(__dirname, (`./public/uploads/${basename}`));
      const worker = await createWorker();
      const { data: { text } } = await worker.recognize(image, { rotateAuto: true });
      await worker.terminate();
      return ctx.body = {
        "data": text,
        "success": true,
        "errCode": "1000",
        "errMsg": ""
      }
    }
  }
  return ctx.body = {
    "data": "",
    "success": false,
    "errCode": "1000",
    "errMsg": "fail ocr"
  }
})

dns.lookup(hostName, (err, add) => {
  https.createServer({
    key: fs.readFileSync('./private_key.pem'),  //私钥文件路径
    cert: fs.readFileSync('./ca-cert.pem')  //证书文件路径
  }, app.callback()).listen(3200, () => {
    console.log(`server running success at https://${add}:3200`)
  });
});


